package com.engine.taskmask.sync;

import com.engine.taskmask.persistence.*;

import java.io.IOException;
import java.io.Serializable;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@SuppressWarnings("serial")
public class SyncServlet implements Serializable {

	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		/*if (req.getParameter("size") == null) {
			resp.sendError(404);
			return;
		}
		int size = Integer.parseInt(req.getParameter("size"));
		if (size == 0) {
			return;
		}
		String account = req.getParameter("account");

		PersistenceManager pm = PMF.get().getPersistenceManager();

		Query query = pm.newQuery(iTask.class);
		// query.se
		query.setFilter("user_id==id");
		query.declareParameters("String id");

		@SuppressWarnings("unchecked")
		List<iTask> serverlist = (List<iTask>) query.execute(account);

		boolean add = false;
		try {

			for (int i = 0; i < size; i++) {

				String in = req.getParameter(i + "");
				if (in == null) {
					resp.sendError(404);
					return;
				}
				byte[] decoded = Base64.decode(in.getBytes("ASCII"),
						Base64.DEFAULT);
				
				ITask rec = new ITask();
				rec.fromByteArray(decoded);

				// rec is a copy of the new uploaded receipt
				iTask rec_s = new iTask(rec.getRdate(), rec.getTaskTitle(),
						rec.getTaskNotes(), rec.getTaskLocation(),
						rec.getTaskCategory(), rec.getTaskPriority(),
						rec.isTaskFlagged(), rec.isTaskProcessed(),
						account, rec.getTaskUniqueIndex());

				// ////////////////////////////
				rec_s.setUpdate(rec.getUpdate());
				rec_s.setSyncdate(rec.getSyncdate());

				for (iTask tmprr : serverlist) {

					if (tmprr.equals(rec_s)) {
						if (rec_s.getUpdate().after(tmprr.getUpdate())) {
							pm.deletePersistent(tmprr);
							pm.makePersistent(rec_s);
							break;
						}
						add = true;
					}

				}
				if (!add) {
					pm.makePersistent(rec_s);
					add = false;
				}
			}

		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} finally {
			pm.close();
		}
*/
	}

}
